package com.ylxin.webflux.handler;

import com.ylxin.webflux.pojo.User;
import com.ylxin.webflux.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.print.attribute.standard.Media;
import javax.xml.ws.Service;
import java.util.List;

/**
 * @author 29048
 * @version V1.0
 * @Project webflux01
 * @Package com.ylxin.webflux.handler
 * @Description: Create by 杨立新 @Date 2022/9/22 17:19
 */

/**Handler
 * 类似于前面的controller,只不过没有指定地址映射
 * 此处使用的是springboot模式
 */
@RestController
public class Controller {

    //Service 会返回数据
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    //根据 id 查询
    public Mono<ServerResponse> findById(ServerRequest request) {
//        return userService.getUserById(id);
        //获取id 的值
        Integer userId = Integer.valueOf(request.pathVariable("id"));
        //空值处理
        Mono<ServerResponse> notFound = ServerResponse.notFound().build();
        //调用 service 方法得到数据
        Mono<User> userMono = this.userService.getUserById(userId);
        //把 userMono 进行转换返回
        //使用 Reactor 操作符 flatMap
        return userMono.flatMap(person ->
            ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(person))
            .switchIfEmpty(notFound);
    }

    //查询所有
    public Mono<ServerResponse> findAllUsers(ServerRequest request) {
        //调用 service 得到结果
        Flux<User> users = this.userService.getAllUser();
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(users);
    }

    //添加
    public Mono<ServerResponse> addUser(ServerRequest request) {
        //得到 user 对象
        Mono<User> userMono = request.bodyToMono(User.class);
        return ServerResponse.ok().build(this.userService.saveUserInfo(userMono));
    }


}
